<template>
	<view class="wechat-login-modal" v-if="visible">
		<view class="modal-overlay" @click="handleClose"></view>
		<view class="modal-content">
			<view class="modal-header">
				<text class="modal-title">微信登录</text>
				<view class="close-btn" @click="handleClose">
					<text class="close-icon">×</text>
				</view>
			</view>
			
			<view class="modal-body">
				<view class="wechat-logo">
					<text class="wechat-icon">💬</text>
				</view>
				
				<view class="qr-code-section">
					<view class="qr-code-container">
						<view class="qr-code-wrapper">
							<image 
								class="qr-code-image" 
								:src="qrCodeUrl" 
								mode="aspectFit"
								@error="handleQRCodeError"
								@load="handleQRCodeLoad"
								v-if="qrCodeUrl"
							/>
							<view class="qr-code-overlay" v-if="!qrCodeUrl">
								<text class="qr-code-placeholder">📱</text>
							</view>
						</view>
						<text class="qr-code-text">
							{{ 
								scanStatus === 'waiting' ? '请使用微信扫码登录' :
								scanStatus === 'scanning' ? '正在验证扫码...' :
								scanStatus === 'success' ? '扫码成功，正在登录...' :
								'请使用微信扫码登录'
							}}
						</text>
						<view class="scan-status" v-if="scanStatus === 'scanning'">
							<text class="status-text">⏳ 验证中...</text>
						</view>
					</view>
					
					<view class="qr-tips">
						<text class="tip-text">1. 打开微信</text>
						<text class="tip-text">2. 点击右上角"+"号</text>
						<text class="tip-text">3. 选择"扫一扫"</text>
						<text class="tip-text">4. 扫描上方二维码</text>
					</view>
				</view>
				
				<button class="wechat-login-btn" @click="handleRefreshQRCode">
					<text class="btn-text">刷新二维码</text>
				</button>
				
				<!-- 模拟扫码按钮（仅用于演示，实际项目中不需要） -->
				<button class="simulate-scan-btn" @click="simulateScan" style="margin-top: 10rpx; background: #ff9500; color: #fff; font-size: 24rpx;">
					<text class="btn-text">模拟手机扫码</text>
				</button>
				
				<view class="divider">
					<text class="divider-text">或</text>
				</view>
				
				<button class="guest-login-btn" @click="handleGuestLogin">
					<text class="btn-text">游客登录</text>
				</button>
				
				<view class="agreement">
					<text class="agreement-text">
						登录即表示同意
						<text class="link">《用户协议》</text>
						和
						<text class="link">《隐私政策》</text>
					</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted } from 'vue'
import { generateQRCodeDataURL, generateWeChatQRData } from '@/utils/qrcode'

interface Props {
	visible: boolean
}

interface Emits {
	(e: 'close'): void
	(e: 'success', userInfo: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 二维码URL
const qrCodeUrl = ref('')

// 当前二维码数据
const currentQRData = ref('')

// 扫码状态
const scanStatus = ref('waiting') // waiting: 等待扫码, scanning: 扫码中, success: 扫码成功, failed: 扫码失败
const scanTimer = ref<number | null>(null)

// 手动触发扫码标志
const manualScanTriggered = ref(false)

// 处理二维码加载错误
const handleQRCodeError = () => {
	console.log('二维码加载失败，使用默认占位符')
	qrCodeUrl.value = ''
}

// 处理二维码加载成功
const handleQRCodeLoad = () => {
	console.log('微信二维码加载成功')
}

// 关闭弹窗
const handleClose = () => {
	emit('close')
}

// 监听弹窗显示状态，自动生成二维码
watch(() => props.visible, (newVisible) => {
	console.log('微信登录弹窗显示状态变化:', { newVisible })
	if (newVisible) {
		// 弹窗显示时，自动生成二维码
		console.log('微信登录弹窗显示，生成二维码')
		generateQRCode()
	}
})

// 开始检测扫码状态
const startScanDetection = () => {
	// 清除之前的定时器
	if (scanTimer.value) {
		clearInterval(scanTimer.value)
	}
	
	console.log('开始检测扫码状态...')
	
	// 模拟真实的扫码检测逻辑
	// 在实际项目中，这里应该调用后端API来检测扫码状态
	scanTimer.value = setInterval(async () => {
		try {
			// 模拟调用后端API检测扫码状态
			// const response = await uni.request({
			// 	url: 'your-api-endpoint/check-scan-status',
			// 	method: 'POST',
			// 	data: { qrData: currentQRData }
			// })
			
			// 这里模拟扫码检测，实际项目中应该根据后端返回的状态来判断
			// 为了演示，我们模拟一个需要用户手动触发的扫码过程
			
			// 检查是否有用户手动点击了"模拟扫码"按钮
			if (manualScanTriggered.value) {
				console.log('检测到手动扫码触发')
				scanStatus.value = 'scanning'
				
				// 模拟扫码验证过程
				setTimeout(() => {
					scanStatus.value = 'success'
					handleScanSuccess()
				}, 1500)
				
				// 清除定时器
				if (scanTimer.value) {
					clearInterval(scanTimer.value)
					scanTimer.value = null
				}
				
				// 重置手动触发标志
				manualScanTriggered.value = false
			}
		} catch (error) {
			console.error('检测扫码状态时出错:', error)
		}
	}, 1000) // 每秒检测一次
}

// 处理扫码成功
const handleScanSuccess = () => {
	uni.showLoading({ title: '登录中...' })
	
	setTimeout(() => {
		uni.hideLoading()
		
		// 生成随机微信账号后四位作为昵称
		const randomWeChat = Math.floor(1000 + Math.random() * 10000).toString().padStart(4, '0')
		const nickname = `微信${randomWeChat}`
		
		// 模拟扫码登录成功
		const mockUserInfo = {
			nickName: nickname,
			nickname: nickname,
			avatar: '/app/icons/120x120.png',
			openid: 'mock_wechat_scan_' + Date.now(),
			loginType: 'wechat_scan',
			wechatAccount: randomWeChat,
			tokenExpires: 15 * 60 // 15分钟有效期
		}
		
		emit('success', mockUserInfo)
		emit('close')
		
		uni.showToast({
			title: '微信扫码登录成功',
			icon: 'success'
		})
		
		// 延迟跳转到my页面
		setTimeout(() => {
			uni.switchTab({ 
				url: '/pages/my/my',
				success: () => {
					console.log('跳转到my页面成功')
				},
				fail: (err) => {
					console.error('跳转到my页面失败:', err)
				}
			})
		}, 600)
	}, 1500)
}

// 生成二维码
const generateQRCode = async () => {
	try {
		const qrData = generateWeChatQRData()
		
		// 使用前端生成二维码
		const qrDataURL = await generateQRCodeDataURL(qrData, {
			width: 200,
			height: 200,
			margin: 2,
			color: {
				dark: '#000000',
				light: '#FFFFFF'
			}
		})
		
		// 保存当前二维码数据
		currentQRData.value = qrData
		
		console.log('生成微信二维码:', { qrData, qrDataURL })
		qrCodeUrl.value = qrDataURL
		
		// 重置扫码状态
		scanStatus.value = 'waiting'
		
		// 重置手动触发标志
		manualScanTriggered.value = false
		
		// 开始检测扫码状态
		startScanDetection()
	} catch (error) {
		console.error('生成微信二维码失败:', error)
		uni.showToast({
			title: '二维码生成失败',
			icon: 'none'
		})
	}
}

// 刷新二维码
const handleRefreshQRCode = () => {
	uni.showLoading({ title: '刷新二维码中...' })
	
	// 生成新的二维码
	generateQRCode()
	
	setTimeout(() => {
		uni.hideLoading()
		uni.showToast({
			title: '二维码已刷新',
			icon: 'success'
		})
	}, 1000)
}

// 模拟扫码（仅用于演示）
const simulateScan = () => {
	console.log('用户点击了模拟扫码按钮')
	manualScanTriggered.value = true
	
	uni.showToast({
		title: '模拟扫码成功',
		icon: 'success'
	})
}

// 游客登录处理
const handleGuestLogin = () => {
	uni.showLoading({ title: '登录中...' })
	
	setTimeout(() => {
		uni.hideLoading()
		
		// 模拟游客登录成功
		const mockUserInfo = {
			nickName: '游客用户',
			nickname: '游客用户',
			avatar: '/app/icons/120x120.png',
			openid: 'guest_' + Date.now(),
			loginType: 'guest',
			tokenExpires: 15 * 60 // 15分钟有效期
		}
		
		emit('success', mockUserInfo)
		emit('close')
		
		uni.showToast({
			title: '登录成功',
			icon: 'success'
		})
		
		// 延迟跳转到my页面
		setTimeout(() => {
			uni.switchTab({ 
				url: '/pages/my/my',
				success: () => {
					console.log('跳转到my页面成功')
				},
				fail: (err) => {
					console.error('跳转到my页面失败:', err)
				}
			})
		}, 600)
	}, 1000)
}

// 组件销毁时清理定时器
onUnmounted(() => {
	if (scanTimer.value) {
		clearInterval(scanTimer.value)
		scanTimer.value = null
	}
})
</script>

<style lang="scss" scoped>
.wechat-login-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 9999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.modal-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
}

.modal-content {
	position: relative;
	width: 85%;
	max-width: 650rpx;
	background: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.3);
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.close-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background: #f5f5f5;
	cursor: pointer;
}

.close-icon {
	font-size: 36rpx;
	color: #999;
}

.modal-body {
	padding: 40rpx 30rpx;
}

.wechat-logo {
	text-align: center;
	margin-bottom: 40rpx;
}

.wechat-icon {
	font-size: 120rpx;
}

.qr-code-section {
	text-align: center;
	margin-bottom: 25rpx;
}

.qr-code-container {
	width: 200rpx;
	height: 200rpx;
	margin: 0 auto 20rpx;
	background: #f8f9fa;
	border: 2rpx dashed #dee2e6;
	border-radius: 15rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
	overflow: hidden;
}

.qr-code-wrapper {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
}

.qr-code-image {
	width: 100%;
	height: 100%;
	object-fit: contain;
}

.qr-code-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f8f9fa;
}

.qr-code-placeholder {
	font-size: 80rpx;
	margin-bottom: 10rpx;
}

.qr-code-text {
	font-size: 22rpx;
	color: #666;
}

.scan-status {
	margin-top: 10rpx;
}

.status-text {
	font-size: 20rpx;
	color: #07c160;
	animation: pulse 1.5s infinite;
}

@keyframes pulse {
	0% { opacity: 1; }
	50% { opacity: 0.5; }
	100% { opacity: 1; }
}

.qr-tips {
	text-align: left;
	margin-bottom: 20rpx;
}

.tip-text {
	display: block;
	font-size: 22rpx;
	color: #666;
	margin-bottom: 8rpx;
	line-height: 1.4;
}

.wechat-login-btn {
	width: 100%;
	height: 88rpx;
	background: #07c160;
	border: none;
	border-radius: 44rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.wechat-login-btn .btn-text {
	color: #fff;
	font-size: 28rpx;
	font-weight: 500;
}

.guest-login-btn {
	width: 100%;
	height: 88rpx;
	background: #f5f5f5;
	border: 1rpx solid #e0e0e0;
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.guest-login-btn .btn-text {
	color: #666;
	font-size: 28rpx;
}

.divider {
	position: relative;
	text-align: center;
	margin: 30rpx 0;
}

.divider::before {
	content: '';
	position: absolute;
	top: 50%;
	left: 0;
	right: 0;
	height: 1rpx;
	background: #e0e0e0;
}

.divider-text {
	background: #fff;
	padding: 0 20rpx;
	color: #999;
	font-size: 24rpx;
}

.agreement {
	text-align: center;
}

.agreement-text {
	font-size: 22rpx;
	color: #999;
	line-height: 1.5;
}

.link {
	color: #07c160;
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
	.modal-content {
		background: #2a2a2a;
	}
	
	.modal-title {
		color: #fff;
	}
	
	.close-btn {
		background: #444;
	}
	
	.close-icon {
		color: #ccc;
	}
	
	.qr-code-container {
		background: #444;
		border-color: #666;
	}
	
	.qr-code-text {
		color: #ccc;
	}
	
	.tip-text {
		color: #ccc;
	}
	
	.guest-login-btn {
		background: #444;
		border-color: #666;
	}
	
	.guest-login-btn .btn-text {
		color: #ccc;
	}
	
	.divider::before {
		background: #666;
	}
	
	.divider-text {
		background: #2a2a2a;
		color: #ccc;
	}
	
	.agreement-text {
		color: #ccc;
	}
}
</style>
